import json

from django.http import HttpResponseRedirect, HttpResponse
from django.shortcuts import render, get_object_or_404
from django.urls import reverse_lazy
from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_exempt
from django.views.generic import TemplateView, CreateView, DeleteView, View, UpdateView
from django.contrib.sessions.backends.db import SessionStore

from django.shortcuts import Http404

from django.contrib import messages

from accounts.auth_session import auth_class, auth_session_clsss
from accounts.models import CustomUser

from assets.models import ProjectSwan, Project, ProductLine, Host, IDC
from utils.tools import ztree_tag, get_hash_token

from .forms import RoleForm, RoleUserForm, RolePermissionLinkForm, PushPermissionMemberMgrForm, HostPermissionCreateForm

from .models import AuthGroup, UserAuthCmdb, AuthNode


class RoleCreateView(CreateView):
    """ 添加角色"""
    template_name = 'auth/role_create.html'
    form_class = RoleForm
    success_url = reverse_lazy('auth_list')


class RoleDeleteView(View):
    """ 删除角色 """
    template_name = None
    model = AuthGroup
    success_url = reverse_lazy('auth_list')

    def get(self, request, *args, **kwargs):
        pk = kwargs.get('pk')
        auth_group = get_object_or_404(AuthGroup, pk=pk)
        auth_group.group_user.clear()
        messages.success(request, f'删除{auth_group}成功')
        auth_group.delete()
        return HttpResponseRedirect(reverse_lazy('auth_list'))


class RoleUpdateView(View):
    """ 更新角色 """

    form_class = RoleForm
    template_name = 'auth/jquery_form.html'

    def get_queryset(self):
        pk = self.kwargs.get('pk')
        auth_group = get_object_or_404(AuthGroup, pk=pk)
        return auth_group

    def get(self, request, *args, **kwargs):
        auth_group = self.get_queryset()
        form = RoleForm(instance=auth_group)
        context = {'form': form, 'pk': self.kwargs.get('pk')}
        return render(self.request, self.template_name, context)

    def post(self, request, *args, **kwargs):
        auth_group = self.get_queryset()
        form = RoleForm(request.POST, instance=auth_group)
        if form.is_valid():
            form.save()
            return HttpResponse(json.dumps({"status": 200, "msg": "ok"}, ensure_ascii=False, indent=4, ))
        context = {'form': form, 'pk': self.kwargs.get('pk')}

        return render(self.request, self.template_name, context)


class RoleListView(TemplateView):
    """ 角色列表页 """
    template_name = 'auth/roles_list.html'

    def get_context_data(self, **kwargs):
        auth_group_objs = AuthGroup.objects.order_by('-date_time')
        group_user_count = {}

        for auth_group in auth_group_objs:
            group_user_count[auth_group.pk] = auth_group.group_user.all().count()
        context = {"auth_group_objs": auth_group_objs, 'group_user_count': group_user_count}
        kwargs.update(context)

        return super().get_context_data(**kwargs)


class RoleUserLinkView(UpdateView):
    """ 角色与用户关联 """
    template_name = 'auth/role_user_link.html'
    form_class = RoleUserForm
    model = AuthGroup
    success_url = '/'

    def get_context_data(self, **kwargs):
        pk = self.kwargs.get('pk')
        auth_group = get_object_or_404(AuthGroup, pk=pk)

        # 获取所有用户, 获取角色,用户已关联的用户名列表
        user_list_obj = CustomUser.objects.all()
        auth_group_u_list = auth_group.group_user.all()
        auth_group_username_list = [x.username for x in auth_group_u_list]

        context = {
            'auth_group_username_list': auth_group_username_list,
            'user_list_obj': user_list_obj,
            'auth_group_u_list': auth_group_u_list,
            'pk': pk

        }
        kwargs.update(context)
        return super().get_context_data(**kwargs)

    def get_success_url(self):
        # 更新角色组所有用户的权限信息
        auth_session_clsss(self.kwargs.get('pk'))
        return super().get_success_url()


class RolePermissionLinkView(TemplateView):
    """ 角色与权限关联 """
    template_name = 'auth/role_permission_link.html'
    form_class = RolePermissionLinkForm

    def get_context_data(self, **kwargs):
        pk = self.kwargs.get('pk')
        auth_group = get_object_or_404(AuthGroup, pk=pk)
        data = None
        group_data = None
        try:
            group_data = get_object_or_404(UserAuthCmdb, group_name=auth_group)
            form = RolePermissionLinkForm(self.request.POST or None, instance=group_data)
        except:
            form = RolePermissionLinkForm(self.request.POST or None)

        context = {'group_data': group_data, 'form': form,
                   'auth_group': auth_group}
        kwargs.update(context)
        return super().get_context_data(**kwargs)

    def post(self, request, *args, **kwargs):
        auth_group_id = self.kwargs.get('pk')
        data = self.get_context_data(**kwargs)
        form = data.get('form')
        if form.is_valid():
            form.save()
            #  刷新权限组所有用户session信息
            auth_session_clsss(auth_group_id)
            # return HttpResponse(json.dumps({"status": 200, "msg": "修改角色与权限关联成功"}, ensure_ascii=False, indent=4, ))
        return render(request, self.template_name, data)


class PushPermissionListView(View):
    ''' 发布权限列表'''
    template_name = 'auth/push_permission_list.html'

    def get(self, request):
        project_swan_obj = ProjectSwan.objects.all()
        return render(request, self.template_name, {'project_swan_obj': project_swan_obj})


# permission

class PushPermissionMemberMgrView(TemplateView):
    """发布项目权限 成员管理"""
    template_name = 'auth/push_permission_member_mgr.html'

    def get_context_data(self, **kwargs):
        # 获取单个对象
        project_swan_obj = get_object_or_404(ProjectSwan, pk=self.kwargs.get('pk'))

        all_user_obj_list = CustomUser.objects.all()
        # 获取此对象关联所有用户
        user_in_project_swan_obj = project_swan_obj.push_user.all()
        print('1111', user_in_project_swan_obj)
        # 获取此对象关联的所有用户名
        user_username_list = [x.username for x in user_in_project_swan_obj]

        context = {
            'project_swan_obj': project_swan_obj,
            'all_user_obj_list': all_user_obj_list,
            'user_username_list': user_username_list,
            'user_in_project_swan_obj': user_in_project_swan_obj,
        }
        kwargs.update(context)

        return super().get_context_data(**kwargs)

    def post(self, request, *args, **kwargs):
        context = self.get_context_data(**kwargs)
        form = PushPermissionMemberMgrForm(request.POST, instance=context.get('project_swan_obj'))
        if form.is_valid():
            form.save()
            # return HttpResponse(json.dumps({"status": 200, "msg": "修改发布项目权限成员管理关联成功"}, ensure_ascii=False, indent=4, ))
        return render(request, self.template_name, context)


class HostUserManagerCountListView(TemplateView):
    """  用戶管理服务器总数列表页面 """
    template_name = 'auth/host_user_manager_count_list.html'

    def get_context_data(self, **kwargs):
        user_object_list = CustomUser.objects.all()

        kwargs.update({'user_object_list': user_object_list})
        return super().get_context_data(**kwargs)


class HostPermissionDetailView(TemplateView):
    """ 用户服务器权限详情页  """
    template_name = 'auth/host_permission_detail.html'

    def get_context_data(self, **kwargs):
        user_pk = self.kwargs.get('pk')
        user_obj = get_object_or_404(CustomUser, pk=user_pk)
        ztree_data = ztree_tag(self.request.user.username, user_pk=user_obj.pk)
        all_auth_node = AuthNode.objects.filter(user_name=user_obj)
        all_auth_node_count = AuthNode.objects.filter(user_name=user_obj).count()

        context = {
            'user_obj': user_obj,
            'ztree_data': ztree_data,
            'all_auth_node': all_auth_node,
            'all_auth_node_count': all_auth_node_count,

        }

        kwargs.update(context)

        return super().get_context_data(**kwargs)


class HostPermissionCreateView(TemplateView):
    """ 用户服务器 添加权限"""
    template_name = 'auth/host_permission_create.html'

    def dispatch(self, request, *args, **kwargs):
        if not request.user.is_superuser:
            raise Http404()
        return super().dispatch(request, *args, **kwargs)

    def get_context_data(self, **kwargs):
        form = HostPermissionCreateForm()

        user_obj = get_object_or_404(CustomUser, pk=self.kwargs.get('userpk'))
        host_obj = get_object_or_404(Host, eth1=self.kwargs.get('hostip'))

        # host_pk = hostip

        business_obj_list = Project.objects.all()
        context = {
            'form': form,
            'user_obj': user_obj,
            'business_obj_list': business_obj_list,
        }
        kwargs.update(context)

        return super().get_context_data(**kwargs)


@method_decorator(csrf_exempt, name='dispatch')
class HostPermissionZtreeView(View):
    """ 服务器授权 """

    def get(self, request, *args, **kwargs):
        #  产品线
        project_pk = self.kwargs.get("name")
        get_line_token = self.kwargs.get("token")
        user_pk = self.kwargs.get("user")

        line_token_check = get_hash_token(self.request.user.username, project_pk)

        user_obj = get_object_or_404(CustomUser, pk=user_pk)

        if get_line_token != line_token_check:
            # 检查两次token是否一致
            content_status = False

        all_auth_node = AuthNode.objects.filter(user_name=user_obj)

        ip_list = [i.node.eth1 for i in all_auth_node]

        node_count = all_auth_node.count()

        if project_pk != "未分类":
            # 项目
            project_obj = Project.objects.get(pk=project_pk)
            # 通过项目查到主机列表
            host_obj_list = Host.objects.filter(projects=project_obj).order_by("create_time")
        else:
            project_obj = "未分类"
            idc_data = IDC.objects.filter(type=1)  # type=1 为核心机房
            # 查出未分配项目的主机
            host_obj_list = Host.objects.filter(business__isnull=True, idc=idc_data).order_by("create_time")
        ztree_data = ztree_tag(request.user.username, user_pk=user_obj.pk)

        content_status = True

        context = {
            "ztree_data": ztree_data,
            "user_obj": user_obj,
            "node_count": node_count,
            "host_obj_list": host_obj_list,
            "ip_list": ip_list,

        }

        kwargs.update(context)

        return render(request, 'auth/HostPermissionZtreeView_tmp.html', context)

    def post(self, request, *args, **kwargs):
        post_obj = request.POST
        user_obj = get_object_or_404(CustomUser, pk=self.kwargs.get("user"))

        is_admin = post_obj.get("auth")
        for i in post_obj.getlist("node_name"):
            host = get_object_or_404(Host, pk=i)
            is_exist = AuthNode.objects.filter(user_name=user_obj, node=host)
            if not is_exist.exists():
                auth_node = AuthNode(user_name=user_obj, auth=is_admin, node=host)
                auth_node.save()

                # todo
                ''' 
                args = {"user": user_data.username,
                        "type": 1,
                        "auth": auth,
                        "node": server.node_name,
                        "ip": server.eth1,
                        "uid": int(3000 + user_data.id),
                        "gid": int(user_data.department.desc_gid),
                        "ssh_key": (user_data.user_key).replace("ssh-rsa ", "")}
                print(args  )
                s = RabApi(args=args)
                print(  s.SendMessage() )  '''
            else:
                print("数据已存在")

        return self.get(request, *args, **kwargs)

    def delete(self, *args, **kwargs):
        """
        删除服务器授权
        user_id, host_id
        """
        # todo is_superuser
        user_pk = self.kwargs.get("user")
        host_pk = self.kwargs.get("token")
        host_obj = get_object_or_404(Host, pk=host_pk)
        user_obj = get_object_or_404(CustomUser, pk=user_pk)
        try:
            auth_node_obj = get_object_or_404(AuthNode, node=host_obj, user_name=user_obj)
            auth_node_obj.node.clean()
            auth_node_obj.user_name.clean()
            auth_node_obj.delete()

            # todo log
            print("删除授权成功")

            ''' 
            args_ = {"user": user_obj.username,
                     "type": 0,
                     "node": host_obj.node_name,
                     "ip": auth_node_obj.node.eth1
                     }
            s = RabApi(args=args)
            print(s.SendMessage())
            
            '''
            return HttpResponse(json.dumps({"status": "200", "message": "删除成功"}, ensure_ascii=False, indent=4))
        except Exception as e:
            print(e)
            return HttpResponse(json.dumps({"status": "404", "message": "无此服务器权限"}, ensure_ascii=False, indent=4))


#  http://192.168.1.167:1991/auth/host/business/
# ?name=20118fbd598c4eb5847eaa6ccf3f090b   (项目名)
# &options=cmdb
# auth=0 ,1 是否是管理员
# &token=75ec8a53f8f5140e78a6eda83b5564045947726a
# &user=472b5c58-37cf-3b0a-81f4-c850d401f44f (user_id)


